<?php

namespace App\Services;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class CacheService
{
    /**
     * 默认缓存时间（分钟）
     */
    const DEFAULT_TTL = 60;
    const LONG_TTL = 1440; // 24小时
    const SHORT_TTL = 5;   // 5分钟

    /**
     * 缓存键前缀
     */
    const PREFIX = 'shop:';

    /**
     * 获取缓存
     */
    public function get(string $key, $default = null)
    {
        $fullKey = $this->getFullKey($key);
        $value = Cache::get($fullKey, $default);
        
        if ($value !== null) {
            Log::debug('Cache hit', ['key' => $fullKey]);
        } else {
            Log::debug('Cache miss', ['key' => $fullKey]);
        }
        
        return $value;
    }

    /**
     * 设置缓存
     */
    public function put(string $key, $value, int $ttl = self::DEFAULT_TTL): bool
    {
        $fullKey = $this->getFullKey($key);
        $result = Cache::put($fullKey, $value, $ttl);
        
        Log::debug('Cache put', [
            'key' => $fullKey,
            'ttl' => $ttl,
            'success' => $result
        ]);
        
        return $result;
    }

    /**
     * 永久缓存
     */
    public function forever(string $key, $value): bool
    {
        $fullKey = $this->getFullKey($key);
        $result = Cache::forever($fullKey, $value);
        
        Log::debug('Cache forever', [
            'key' => $fullKey,
            'success' => $result
        ]);
        
        return $result;
    }

    /**
     * 删除缓存
     */
    public function forget(string $key): bool
    {
        $fullKey = $this->getFullKey($key);
        $result = Cache::forget($fullKey);
        
        Log::debug('Cache forget', [
            'key' => $fullKey,
            'success' => $result
        ]);
        
        return $result;
    }

    /**
     * 清空所有缓存
     */
    public function flush(): bool
    {
        $result = Cache::flush();
        
        Log::info('Cache flushed', ['success' => $result]);
        
        return $result;
    }

    /**
     * 记住缓存（如果不存在则执行回调）
     */
    public function remember(string $key, callable $callback, int $ttl = self::DEFAULT_TTL)
    {
        $fullKey = $this->getFullKey($key);
        
        return Cache::remember($fullKey, $ttl, function () use ($callback, $key) {
            Log::debug('Cache remember callback', ['key' => $key]);
            return $callback();
        });
    }

    /**
     * 记住永久缓存
     */
    public function rememberForever(string $key, callable $callback)
    {
        $fullKey = $this->getFullKey($key);
        
        return Cache::rememberForever($fullKey, function () use ($callback, $key) {
            Log::debug('Cache remember forever callback', ['key' => $key]);
            return $callback();
        });
    }

    /**
     * 标签化缓存
     */
    public function tags(array $tags): \Illuminate\Cache\TaggedCache
    {
        return Cache::tags($tags);
    }

    /**
     * 商品相关缓存
     */
    public function getProduct(int $productId)
    {
        return $this->remember(
            "product:{$productId}",
            fn() => \App\Models\Product::with(['images', 'variants', 'categories'])->find($productId),
            self::LONG_TTL
        );
    }

    public function forgetProduct(int $productId): void
    {
        $this->forget("product:{$productId}");
        $this->forget("products:list");
        $this->forget("products:featured");
    }

    /**
     * 商品列表缓存
     */
    public function getProductsList(array $filters = [])
    {
        $key = 'products:list:' . md5(serialize($filters));
        
        return $this->remember($key, function () use ($filters) {
            return \App\Models\Product::with(['images', 'variants'])
                ->when($filters['category'] ?? null, function ($query, $category) {
                    $query->whereHas('categories', function ($q) use ($category) {
                        $q->where('slug', $category);
                    });
                })
                ->when($filters['search'] ?? null, function ($query, $search) {
                    $query->where('name', 'like', "%{$search}%");
                })
                ->when($filters['min_price'] ?? null, function ($query, $minPrice) {
                    $query->where('price', '>=', $minPrice);
                })
                ->when($filters['max_price'] ?? null, function ($query, $maxPrice) {
                    $query->where('price', '<=', $maxPrice);
                })
                ->where('is_active', true)
                ->orderBy('created_at', 'desc')
                ->paginate(12);
        }, self::SHORT_TTL);
    }

    public function forgetProductsList(): void
    {
        $this->forget("products:list");
        $this->forget("products:featured");
    }

    /**
     * 用户相关缓存
     */
    public function getUser(int $userId)
    {
        return $this->remember(
            "user:{$userId}",
            fn() => \App\Models\User::with(['addresses'])->find($userId),
            self::LONG_TTL
        );
    }

    public function forgetUser(int $userId): void
    {
        $this->forget("user:{$userId}");
    }

    /**
     * 订单相关缓存
     */
    public function getOrder(string $orderNumber)
    {
        return $this->remember(
            "order:{$orderNumber}",
            fn() => \App\Models\Order::with(['items.product.images', 'items.variant.images'])->where('order_number', $orderNumber)->first(),
            self::DEFAULT_TTL
        );
    }

    public function forgetOrder(string $orderNumber): void
    {
        $this->forget("order:{$orderNumber}");
    }

    /**
     * 购物车相关缓存
     */
    public function getCart(int $userId, string $sessionId)
    {
        return $this->remember(
            "cart:{$userId}:{$sessionId}",
            fn() => \App\Models\Cart::with(['items.product.images', 'items.variant.images'])->where('user_id', $userId)->where('session_id', $sessionId)->first(),
            self::SHORT_TTL
        );
    }

    public function forgetCart(int $userId, string $sessionId): void
    {
        $this->forget("cart:{$userId}:{$sessionId}");
    }

    /**
     * 系统设置缓存
     */
    public function getSystemSettings()
    {
        return $this->rememberForever('system:settings', function () {
            return \App\Models\SystemSetting::all()->pluck('value', 'key');
        });
    }

    public function forgetSystemSettings(): void
    {
        $this->forget('system:settings');
    }

    /**
     * 分类缓存
     */
    public function getCategories()
    {
        return $this->rememberForever('categories:all', function () {
            return \App\Models\Category::with(['children'])->whereNull('parent_id')->get();
        });
    }

    public function forgetCategories(): void
    {
        $this->forget('categories:all');
    }

    /**
     * 统计缓存
     */
    public function getStats(string $type, array $filters = [])
    {
        $key = "stats:{$type}:" . md5(serialize($filters));
        
        return $this->remember($key, function () use ($type, $filters) {
            return match($type) {
                'orders' => $this->getOrderStats($filters),
                'products' => $this->getProductStats($filters),
                'users' => $this->getUserStats($filters),
                default => null,
            };
        }, self::SHORT_TTL);
    }

    private function getOrderStats(array $filters): array
    {
        $query = \App\Models\Order::query();
        
        if (!empty($filters['start_date'])) {
            $query->where('created_at', '>=', $filters['start_date']);
        }
        if (!empty($filters['end_date'])) {
            $query->where('created_at', '<=', $filters['end_date']);
        }
        
        return [
            'total' => $query->count(),
            'total_amount' => $query->sum('total_amount'),
            'pending' => $query->where('status', 'pending')->count(),
            'processing' => $query->where('status', 'processing')->count(),
            'completed' => $query->where('status', 'delivered')->count(),
        ];
    }

    private function getProductStats(array $filters): array
    {
        $query = \App\Models\Product::query();
        
        return [
            'total' => $query->count(),
            'active' => $query->where('is_active', true)->count(),
            'inactive' => $query->where('is_active', false)->count(),
            'featured' => $query->where('is_featured', true)->count(),
        ];
    }

    private function getUserStats(array $filters): array
    {
        $query = \App\Models\User::query();
        
        return [
            'total' => $query->count(),
            'active' => $query->where('is_active', true)->count(),
            'inactive' => $query->where('is_active', false)->count(),
        ];
    }

    /**
     * 获取完整缓存键
     */
    private function getFullKey(string $key): string
    {
        return self::PREFIX . $key;
    }

    /**
     * 批量删除相关缓存
     */
    public function forgetRelated(string $type, int $id): void
    {
        match($type) {
            'product' => $this->forgetProduct($id),
            'user' => $this->forgetUser($id),
            'category' => $this->forgetCategories(),
            'settings' => $this->forgetSystemSettings(),
            default => null,
        };
    }
}
